package org.summerframework.component.security.spring;

import org.summerframework.component.security.AdminSave;
import org.summerframework.component.security.core.interceptor.SecurityInterceptor;
import org.summerframework.component.security.role.service.dto.UserRoleRelDTO;
import org.summerframework.component.security.security.service.DefaultRoleService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static org.summerframework.component.security.security.service.DefaultRoleService.PERMISSIONS_LIST_KEY;
import static org.summerframework.component.security.security.service.DefaultRoleService.ROLE_KEY;

/**
 * @author 石超
 * @version v1.0.0
 */
public class SecurityRoleServiceImpl implements SecurityRoleService {
    @Resource
    private AdminSave adminSave;

    @Resource
    private DefaultRoleService defaultRoleService;

    @Override
    public List<GrantedAuthority> getRole(Long userId) {
        List<String> objects = defaultRoleService.<UserRoleRelDTO>get(userId.toString(), ROLE_KEY).stream().map(userRoleRelDTO -> "ROLE_" + userRoleRelDTO.getRoleCode()).collect(Collectors.toList());
        objects.addAll(defaultRoleService.get(userId.toString(), PERMISSIONS_LIST_KEY));
        objects.add(SecurityInterceptor.ANY);

        if (adminSave.isAdmin(userId) && !objects.contains(ROLE_ADMIN)) {
            objects.add(ROLE_ADMIN);
        }

        return objects.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }
}
